package com.plant.college.service.impl;

import cn.hutool.json.JSON;
import com.plant.college.domain.College;
import com.plant.college.domain.Physician;
import com.plant.college.feign.PhysicianFeign;
import com.plant.college.mapper.CollegeMapper;
import com.plant.college.service.CollegeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CollegeServiceImpl implements CollegeService {

    @Autowired
    CollegeMapper collegeMapper;

    @Autowired
    PhysicianFeign physicianFeign;

    @Override
    public List<College> getCollege(College collegeParam) {
        // 从远程服务获取所有医生的信息列表
        List<Physician> allPhysicians = physicianFeign.findAll();

        // 将所有医生的信息转换为一个Map，键为医生ID，值为医生对象
        Map<Integer, Physician> physicianMap = allPhysicians.stream()
                .collect(Collectors.toMap(Physician::getId, physician -> physician));

        // 通过collegeMapper查询数据库，获取与特定参数匹配的所有学院信息
        List<College> originalColleges = collegeMapper.getCollege(collegeParam);

        // 返回处理后的学院列表
        return originalColleges.stream()
                .map(processedCollege -> {
                    // 获取学院对象的医生ID
                    Integer doctorId = processedCollege.getDoctor_id();

                    // 如果physicianMap中存在该医生ID，则更新学院信息；否则，保留原样
                    if (physicianMap.containsKey(doctorId)) {
                        return updateCollegeWithPhysicianInfo(processedCollege, physicianMap.get(doctorId));
                    } else {
                        return processedCollege;
                    }
                })
                .collect(Collectors.toList());

    }

    private College updateCollegeWithPhysicianInfo(College college, Physician physician) {
        college.setCity(physician.getCity());
        college.setDname(physician.getName());
        college.setAddress(physician.getAddress());
        college.setDesc(physician.getDesc());
        return college;
    }

    @Override
    public College findByIdCollege(Integer id) {
        return collegeMapper.findByIdCollege(id);
    }


}
